﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Data;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.SiteDefinition.MasterPage;
using Kiiro.Model;
using Kiiro.SiteDefinition.Core;
using Kiiro.SiteDefinition.ControlTemplates;

namespace Kiiro.SiteDefinition.PortalPages
{
    public partial class NewProject : BasePage
    {
        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) customFieldCollection; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachments; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) formButtons; }
        }

        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );

            CustomFields.ControlMode = SPControlMode.New;
            Buttons.SaveButton.ControlMode = SPControlMode.New;
            Buttons.CancelButton.ControlMode = SPControlMode.New;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            Attachments.MaxLength = 1;
            Attachments.FileFormat = "mpp";

            CustomFields.EntityType = typeof ( Project );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( Project ), 0, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.New;

            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            litTitle.Text = "New Project";

            Buttons.SaveButton.Visible = PermissionBitsProjects [ 0 ];
        }

        internal override bool Save ( )
        {
            if ( PermissionBitsProjects [ 0 ] )
            {
                Project project = new Project ( );

                project.Title = txtProjectTitle.Text.Trim ( );
                project.ServerRelativeWebUrl = txtServerRelativeWebUrl.Text.Trim ( );
                project.ProjectStatus = ( ProjectStatus ) int.Parse ( rbProjectStatus.SelectedValue );

                List<Attachment> attachments = Attachments.GetAttachments ( );

                if ( attachments.Count > 0 )
                {
                    project.AttachmentList.AddRange ( attachments );
                }
                else
                {
                    DateTime dt;

                    ValidationMessage message = null;
                    if ( DateTime.TryParse ( txtStartDate.Text, out dt ) || string.IsNullOrEmpty ( txtStartDate.Text ) )
                    {
                        project.StartDate = string.IsNullOrEmpty ( txtStartDate.Text ) ? DateTimeHelpers.Empty : DateTime.Parse ( txtStartDate.Text );
                    }
                    else
                    {
                        message = new ValidationMessage ( ValidationSeverity.Validation, "Start date is not in the correct format. (e.g: 05/17/2007)" );
                        project.StartDateMessage.Add ( message );
                    }

                    if ( DateTime.TryParse ( txtEndDate.Text, out dt ) || string.IsNullOrEmpty ( txtEndDate.Text ) )
                    {
                        project.EndDate = string.IsNullOrEmpty ( txtEndDate.Text ) ? DateTimeHelpers.Empty : DateTime.Parse ( txtEndDate.Text );
                    }
                    else
                    {
                        message = new ValidationMessage ( ValidationSeverity.Validation, "End date is not in the correct format. (e.g: 05/17/2007)" );
                        project.EndDateMessage.Add ( message );
                    }
                }

                project.TimeMetric = ( TimeMetric ) int.Parse ( rblTimeMetric.SelectedValue );
                project.Description = txtProjectDescription.Text.Trim ( );
                project.SummaryNote = txtProjectSummary.Text.Trim ( );
                project.LastUpdatedSummaryNote = string.IsNullOrEmpty ( CurrentUser.FullName ) ? "Uknown" : CurrentUser.FullName;

                // Work
                project.ActualWork = 0;
                project.ProjectedWork = 0;
                project.TotalWork = 0;

                // set stats to 0
                project.TaskStats = new List<string> { "0", "0" };
                project.IssueStats = new List<string> { "0", "0" };
                project.DocumentStats = new List<string> { "0", "0" };
                project.DiscussionStats = new List<string> { "0", "0" };
                project.CreatedBy = CurrentUser;
                project.ServerRelativeUrl = ServerRelativeUrl.Length > 1 ? ServerRelativeUrl : "/";
                project.SiteCollectionId = SiteCollectionId;

                project.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                project.IsWPSandboxActivated = ckbWPSandboxEnabled.Checked;
                project.WPSandboxNavText = project.IsWPSandboxActivated ? txtWPSandboxNavText.Text : default ( string );

                project.EditType = EditType.Created;

                ProjectsModel.Save ( project, SiteCollectionId, ServerRelativeUrl );
                Redirect ( project );
            }
            return true;
        }

        internal override string Cancel ( )
        {
            string url = Constants.PortalFileUrls.ProjectsActive;

            using ( SPWeb web = SPHelpers.GetPortalWeb ( SiteCollectionId, ServerRelativeUrl ) )
            {
                string webUrl = web.Url;
                url = webUrl == "/" ? webUrl + url.Substring ( 1 ) : webUrl + url;
            }

            if ( Request.Params [ "Source" ] != null )
            {
                url = Request.Params [ "Source" ];
            }

            return url;
        }

        private void Redirect ( Project project )
        {
            if ( project.IsValid ( ) )
            {
                Response.Redirect ( project.ServerRelativeWebUrl );
            }
            else
            {
                KiiroMaster.V2ErrorsList.ErrorMessages.Clear ( );
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( "There are some submission errors with the form. Errors will be shown in red below the fields." );
                KiiroMaster.V2ErrorsList.OperationStatus = OperationStatus.Failure;

                lblProjectTitleMessage.Text = FormattingHelpers.GetErrorMessageText ( project.TitleMessage );
                lblServerRelativeWebUrlMessage.Text = FormattingHelpers.GetErrorMessageText ( project.ServerRelativeWebUrlMessage );
                lblProjectStatusMessage.Text = FormattingHelpers.GetErrorMessageText ( project.ProjectStatusMessage );
                Attachments.ValidationMessage = FormattingHelpers.GetErrorMessageText ( project.ProjectPlanBytesMessage );
                lblEndDateMessage.Text = FormattingHelpers.GetErrorMessageText ( project.EndDateMessage );
                lblStartDateMessage.Text = FormattingHelpers.GetErrorMessageText ( project.StartDateMessage );
                lblProjectSummaryMessage.Text = FormattingHelpers.GetErrorMessageText ( project.SummaryNoteMessage );
                lblProjectDescriptionMessage.Text = FormattingHelpers.GetErrorMessageText ( project.DescriptionMessage );
                lblWPSandboxNavTextMessage.Text = FormattingHelpers.GetErrorMessageText ( project.WPSandboxNavTextMessage );
            }
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.PortalPages/Projects/NewProject.aspx.cs $
 * 
 * 17    2/08/10 2:28p Camerons
 * 
 * 16    1/11/10 11:51a Camerons
 * 
 * 13    10/28/09 1:40p Adamw
 * 
 * 12    10/27/09 5:53p Adamw
 * accomodations for moving plan file to document library:
 * -moved saving of plan out of ProjectsDA and into DocumentModel -->
 * DocumentDA
 * -added call to save project plan file to document library from
 * ProjectsModel
 * -changed New/Edit Project pages to pass in Attachment collection
 * 
 * 11    16/10/09 5:40p Shafia
 * Set Attachments Properties MaxLength, and FileFormat to allow one file
 * and .mpp files only.
 * 
 * 10    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 9     29/09/09 12:40p Shafia
 * Implemented WebPart at project level
 * 
 * 8     23/09/09 4:34p Shafia
 * implemented the new WelcomeMessagePanel user control on Projects,
 * Users, CustomLists, Work, Documents, and Discussions pages.
 * Links are being displayed based on PermissionsBits[Entity]
 * 
 * 7     31/08/09 12:20p Shafia
 * 
 * 6     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/